package cn.bmbanjia.zebra2024.frame.exception;

import cn.bmbanjia.zebra2024.frame.resp.Resp;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Resp<Void> handleException(Exception e) {
        log.error("GlobalExceptionHandler handleException", e);
        return Resp.error(ExceptionUtil.getMessage(e));
    }

    @ExceptionHandler(value = NoResourceFoundException.class)
    public Resp<Void> handleNoResourceFoundException(NoResourceFoundException e) {
        log.error("GlobalExceptionHandler handleNoResourceFoundException", e);
        return Resp.error(HttpStatus.HTTP_NOT_FOUND, ExceptionUtil.getMessage(e));
    }

    @ExceptionHandler(value = NotLoginException.class)
    public Resp<Void> handleNotLoginException(NotLoginException e) {
        log.error("GlobalExceptionHandler handleNoHandlerFoundException", e);
        return Resp.error(HttpStatus.HTTP_UNAUTHORIZED, ExceptionUtil.getMessage(e));
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public Resp<Void> handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("GlobalExceptionHandler handleNoHandlerFoundException", e);
        return Resp.error(e.getStatusCode().value(), ExceptionUtil.getMessage(e));
    }

    @ExceptionHandler(value = CodeException.class)
    public Resp<Void> handleCodeException(CodeException ce) {
        log.error("GlobalExceptionHandler handleCodeException : {}", ce.getMessage());
        return Resp.error(ce.getMessage());
    }

}
